/**
 * 事件总线工具
 * 简化组件间的事件传递，减少props和emit的复杂性
 */

class EventBus {
  constructor() {
    this.events = {};
    this.maxListeners = 100;
  }

  /**
   * 监听事件
   * @param {string} event 事件名
   * @param {Function} callback 回调函数
   * @param {Object} context 上下文
   * @returns {Function} 取消监听的函数
   */
  on(event, callback, context = null) {
    if (!this.events[event]) {
      this.events[event] = [];
    }

    if (this.events[event].length >= this.maxListeners) {
      console.warn(`事件 ${event} 的监听器数量已达到上限 ${this.maxListeners}`);
      return () => {};
    }

    const listener = { callback, context };
    this.events[event].push(listener);

    // 返回取消监听的函数
    return () => {
      this.off(event, callback, context);
    };
  }

  /**
   * 监听一次性事件
   * @param {string} event 事件名
   * @param {Function} callback 回调函数
   * @param {Object} context 上下文
   * @returns {Function} 取消监听的函数
   */
  once(event, callback, context = null) {
    const onceCallback = (...args) => {
      callback.apply(context, args);
      this.off(event, onceCallback, context);
    };
    return this.on(event, onceCallback, context);
  }

  /**
   * 取消监听事件
   * @param {string} event 事件名
   * @param {Function} callback 回调函数
   * @param {Object} context 上下文
   */
  off(event, callback, context = null) {
    if (!this.events[event]) return;

    this.events[event] = this.events[event].filter(listener => {
      return !(listener.callback === callback && listener.context === context);
    });

    if (this.events[event].length === 0) {
      delete this.events[event];
    }
  }

  /**
   * 触发事件
   * @param {string} event 事件名
   * @param {...any} args 参数
   */
  emit(event, ...args) {
    if (!this.events[event]) return;

    this.events[event].forEach(listener => {
      try {
        listener.callback.apply(listener.context, args);
      } catch (error) {
        console.error(`事件 ${event} 的监听器执行出错:`, error);
      }
    });
  }

  /**
   * 移除所有监听器
   * @param {string} event 事件名（可选）
   */
  removeAllListeners(event = null) {
    if (event) {
      delete this.events[event];
    } else {
      this.events = {};
    }
  }

  /**
   * 获取事件监听器数量
   * @param {string} event 事件名
   * @returns {number} 监听器数量
   */
  listenerCount(event) {
    return this.events[event] ? this.events[event].length : 0;
  }

  /**
   * 获取所有事件名
   * @returns {Array} 事件名数组
   */
  eventNames() {
    return Object.keys(this.events);
  }

  /**
   * 销毁事件总线
   */
  destroy() {
    this.removeAllListeners();
  }
}

// 创建全局事件总线实例
const eventBus = new EventBus();

// 消息相关事件常量
export const MESSAGE_EVENTS = {
  // 消息操作事件
  MESSAGE_COPY: 'message:copy',
  MESSAGE_RETRACT: 'message:retract',
  MESSAGE_DELETE: 'message:delete',
  MESSAGE_QUOTE: 'message:quote',
  MESSAGE_EDIT: 'message:edit',
  MESSAGE_FORWARD: 'message:forward',
  
  // 消息状态事件
  MESSAGE_SENT: 'message:sent',
  MESSAGE_DELIVERED: 'message:delivered',
  MESSAGE_READ: 'message:read',
  MESSAGE_FAILED: 'message:failed',
  MESSAGE_RETRACTED: 'message:retracted',
  
  // 消息交互事件
  MESSAGE_CLICK: 'message:click',
  MESSAGE_HOVER: 'message:hover',
  MESSAGE_DOUBLE_CLICK: 'message:double-click',
  
  // 消息内容事件
  MESSAGE_CONTENT_LOADED: 'message:content:loaded',
  MESSAGE_IMAGE_LOADED: 'message:image:loaded',
  MESSAGE_VOICE_PLAY: 'message:voice:play',
  MESSAGE_VOICE_PAUSE: 'message:voice:pause',
  MESSAGE_VOICE_STOP: 'message:voice:stop',
  
  // 消息列表事件
  MESSAGE_LIST_SCROLL: 'message:list:scroll',
  MESSAGE_LIST_LOAD_MORE: 'message:list:load-more',
  MESSAGE_LIST_REACH_TOP: 'message:list:reach-top',
  MESSAGE_LIST_REACH_BOTTOM: 'message:list:reach-bottom'
};

// 聊天相关事件常量
export const CHAT_EVENTS = {
  // 聊天状态事件
  CHAT_OPEN: 'chat:open',
  CHAT_CLOSE: 'chat:close',
  CHAT_SWITCH: 'chat:switch',
  CHAT_CLEAR: 'chat:clear',
  
  // 聊天操作事件
  CHAT_SEND_MESSAGE: 'chat:send-message',
  CHAT_TYPING: 'chat:typing',
  CHAT_STOP_TYPING: 'chat:stop-typing',
  
  // 聊天成员事件
  CHAT_MEMBER_JOIN: 'chat:member:join',
  CHAT_MEMBER_LEAVE: 'chat:member:leave',
  CHAT_MEMBER_UPDATE: 'chat:member:update'
};

// 用户相关事件常量
export const USER_EVENTS = {
  // 用户状态事件
  USER_ONLINE: 'user:online',
  USER_OFFLINE: 'user:offline',
  USER_TYPING: 'user:typing',
  USER_STOP_TYPING: 'user:stop-typing',
  
  // 用户信息事件
  USER_INFO_UPDATE: 'user:info:update',
  USER_AVATAR_UPDATE: 'user:avatar:update',
  USER_STATUS_UPDATE: 'user:status:update'
};

// 文件相关事件常量
export const FILE_EVENTS = {
  // 文件上传事件
  FILE_UPLOAD_START: 'file:upload:start',
  FILE_UPLOAD_PROGRESS: 'file:upload:progress',
  FILE_UPLOAD_SUCCESS: 'file:upload:success',
  FILE_UPLOAD_ERROR: 'file:upload:error',
  
  // 文件下载事件
  FILE_DOWNLOAD_START: 'file:download:start',
  FILE_DOWNLOAD_PROGRESS: 'file:download:progress',
  FILE_DOWNLOAD_SUCCESS: 'file:download:success',
  FILE_DOWNLOAD_ERROR: 'file:download:error'
};

// 系统相关事件常量
export const SYSTEM_EVENTS = {
  // 系统状态事件
  SYSTEM_CONNECTED: 'system:connected',
  SYSTEM_DISCONNECTED: 'system:disconnected',
  SYSTEM_RECONNECTING: 'system:reconnecting',
  SYSTEM_ERROR: 'system:error',
  
  // 系统通知事件
  SYSTEM_NOTIFICATION: 'system:notification',
  SYSTEM_ANNOUNCEMENT: 'system:announcement',
  SYSTEM_UPDATE: 'system:update'
};

// 导出所有事件常量
export const ALL_EVENTS = {
  ...MESSAGE_EVENTS,
  ...CHAT_EVENTS,
  ...USER_EVENTS,
  ...FILE_EVENTS,
  ...SYSTEM_EVENTS
};

// Vue插件形式的事件总线
export const EventBusPlugin = {
  install(Vue) {
    Vue.prototype.$eventBus = eventBus;
    Vue.prototype.$MESSAGE_EVENTS = MESSAGE_EVENTS;
    Vue.prototype.$CHAT_EVENTS = CHAT_EVENTS;
    Vue.prototype.$USER_EVENTS = USER_EVENTS;
    Vue.prototype.$FILE_EVENTS = FILE_EVENTS;
    Vue.prototype.$SYSTEM_EVENTS = SYSTEM_EVENTS;
  }
};

// 导出事件总线实例
export default eventBus;